<?php

namespace App\Modules\Coupon;


use App\Exceptions\StandardException;
use App\Modules\Coupon\Models\Coupon;
use App\Modules\Coupon\Models\UserCoupon;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Query\Builder;

class Manager
{
    public static function sendCoupon(Coupon $coupon, User $user)
    {
        return UserCoupon::query()
            ->create([
                'shop_id' => $coupon->shop_id,
                'user_id' => $user->id,
                'coupon_id' => $coupon->id,
                'type' => $coupon->type,
                'title' => $coupon->title,
                'price_limit' => $coupon->price_limit,
                'money' => $coupon->money,
                'applicable' => $coupon->applicable,
                'is_gift' => $coupon->is_gift,
                'expiration_date' => Carbon::now()->addDays($coupon->shelf_life)->toDateString(),
            ]);
    }

    public static function useCoupon($userCoupon, $useId)
    {
        $userCoupon->use_id = $useId;
        $userCoupon->use_time = Carbon::now()->toDateTimeString();
        $userCoupon->save();
        return $userCoupon;
    }

    public static function getUseableCoupon(User $user, $type, $useId)
    {
        return UserCoupon::query()
            ->where('user_id', $user->id)
            ->where('type', $type)
            ->where('expiration_date', ">=", Carbon::now()->toDateString())
            ->where(function (Builder $q) use($useId) {
                return $q->whereNull('applicable')
                    ->orWhereJsonContains('applicable', [(string) $useId]);
            });
    }
}
